from django.shortcuts import render, redirect, HttpResponse
from django import forms
from accounts.utils.bootstrap import BootStrapForm
from accounts.utils.encrypt import md5
from accounts import models as ac_models
from accounts.utils.code import check_code
from social.models import (
    UserInform
)
from accounts.models import (
    UserAccount,
    AncientPoem
)
from io import BytesIO
import random


def loadindex(request):
    user_info = request.session.get('info', {})
    user_id = user_info.get('id')
    username = None
    if user_id:
        try:
            user_account = UserAccount.objects.get(id=user_id)
            username = user_account.username
        except UserAccount.DoesNotExist:
            pass

    # 随机选择一条古诗词
    poems = AncientPoem.objects.all()
    if poems:
        random_poem = random.choice(poems)
        poem_text = random_poem.poem_text
        source = random_poem.source
    else:
        poem_text = "没有找到古诗词"
        source = ""

    content = {
        'user_id': user_id,
        'username': username,
        "word": poem_text,
        "citation": source
    }
    print(content)
    return render(request, 'mainpage.html', {'content': content})


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True,
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)


def login(request):
    """登录"""
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功，获取到的用户名和密码
        print(form.cleaned_data)
        # 验证码的校验
        user_input_code = form.cleaned_data.pop('code')
        # 获取session中存储的验证码
        code = request.session.get('image_code', '')
        if code.upper() != user_input_code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})
        # 去数据库校验用户名和密码是否正确,获取用户对象,None
        admin_object = ac_models.UserAccount.objects.filter(
            **form.cleaned_data).first()
        # admin_object = models.Admin.objects.filter(username=form.cleaned_data['username'], password=form.cleaned_data['password']).first()
        if not admin_object:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # 用户名和密码输入正确
        # 网站生成随机字符串；写到用户浏览器的cookie中，再写入到session中
        request.session['info'] = {
            'id': admin_object.id, 'name': admin_object.username}
        # session可以保存7天
        request.session.set_expiry(60*60*24*7)

        return redirect(f'/social/{admin_object.username}')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    # 调用pillow函数，生成图片
    img, code_string = check_code()

    # 写入到自己的session中（以便后续获取验证码再进行校验）
    request.session['image_code'] = code_string
    # 给Session设置60s超时
    request.session.set_expiry(60)

    print(code_string)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    """注销"""

    request.session.clear()

    return redirect('/login/')


class RegisterForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True,
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput,
        required=True,
    )
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput,
        required=True
    )

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        if password != confirm_password:
            raise forms.ValidationError("两次密码输入不一致")


def register(request):
    """用户注册"""
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterForm(request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # MD5 加密密码
        md5_password = md5(password)
        # 检查用户名是否已存在
        if ac_models.UserAccount.objects.filter(username=username).exists():
            form.add_error('username', '该用户名已被使用，请选择一个新的用户名')
        else:
            user = ac_models.UserAccount(
                username=username, password=md5_password)
            user.save()
            user_inform = UserInform(user=user)
            user_inform.save()
            return redirect('/login/')  # 重定向到登录页面
    return render(request, 'register.html', {'form': form})
